package com.fly.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by frinder on 2018/3/8.
 */
@Slf4j
@Service
public class MyJdbcService {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    /**
     * @param sql
     * @param queryParameterSource
     * @return
     */
    public <T> List<T> queryList(Class<T> clazz, String sql, MapSqlParameterSource queryParameterSource) {
        return jdbcTemplate.query(sql, queryParameterSource, new BeanPropertyRowMapper<>(clazz));
    }

    /**
     * @param sql
     * @param queryParams
     * @param <T>
     * @return
     */
    public <T> List<T> queryList(Class<T> clazz, String sql, Map<String, Object> queryParams) {
        return jdbcTemplate.query(sql, queryParams, new BeanPropertyRowMapper<>(clazz));
    }

    /**
     * @param sql
     * @param queryParameterSource
     * @param <T>
     * @return
     */
    public <T> T queryOne(Class<T> clazz, String sql, MapSqlParameterSource queryParameterSource) {
        try {
            return jdbcTemplate.queryForObject(sql, queryParameterSource, new BeanPropertyRowMapper<>(clazz));
        } catch (Exception e) {
            // log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * @param sql
     * @param queryParams
     * @param <T>
     * @return
     */
    public <T> T queryOne(Class<T> clazz, String sql, Map<String, Object> queryParams) {
        try {
            return jdbcTemplate.queryForObject(sql, queryParams, new BeanPropertyRowMapper<>(clazz));
        } catch (Exception e) {
            // log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * @param sql
     * @param queryParameterSource
     * @return
     */
    public Map<String, Object> queryMap(String sql, MapSqlParameterSource queryParameterSource) {
        return jdbcTemplate.queryForMap(sql, queryParameterSource);
    }

    /**
     * @param sql
     * @param queryParams
     * @return
     */
    public Map<String, Object> queryMap(String sql, Map<String, Object> queryParams) {
        return jdbcTemplate.queryForMap(sql, queryParams);
    }

}
